import 'package:flutter_give/repository/api.dart';
import 'package:rapid_kit/rapid_kit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';

import '../../common_ui/dialog/dialog_factory.dart';
import '../../repository/datas/TangeEqTime.dart';
import '../../theme.dart';

/// 更多设置页面
class MoresettingPage extends StatefulWidget {
  final String deviceId;
  final String Eqid;

  const MoresettingPage(
      {super.key, required this.deviceId, required this.Eqid});

  @override
  State<StatefulWidget> createState() {
    return _MoresettingPageState();
  }
}

class _MoresettingPageState extends State<MoresettingPage> {
  late String _deviceId;
  late String _Eqid;

  // 指令示例
  late Pipe _pipe;

  // 设别开关
  // bool _isSwitched = false;

  // 设备开关
  int _isSwitched = 0;

  // 设备时区
  String _TZ = "--";

  // 设备时间
  String _TZTIME = "--";

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;
    _Eqid = widget.Eqid;

    LogUtils.w("设备ID: $_deviceId");

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    _gettimedata(_deviceId);

    // 创建实例
    _pipe = Pipe.create(_deviceId);
    // 连接设备
    _pipe.establish();

    // 2. 监听“连接状态”以作出响应
    // _pipe.listen((state) {
    //   LogUtils.w(state);
    //   if (state == PipeState.established) {
    //     // 连接成功建立，可以启动视频播放、发送指令或者其他操作了
    //     _onQuality();
    //   }
    // });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("页面渲染完毕");
      _onQuality();
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 销毁实例
    _pipe.abolish();
    _pipe.destroy();
  }

  Future<bool> _onWillPop() async {
    // HomePageState.globalKeytwo.currentState?.reloadData();
    return true;
  }

  void _onQuality() async {
    LogUtils.w("========执行1=======");
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行2=======");
    final resp = await InstructStandard.deviceSwitch(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data);
      setState(() {
        _isSwitched = resp.data ?? 1;
      });
    } else {
      showToast("获取设备失败");
    }
  }

  void _gettimedata(ID) async {
    TangeEqTime data = await Api.instance.eqtimedata(ID: ID);
    if (data != null) {
      setState(() {
        _TZ = data.tz ?? "";
        _TZTIME = data.time ?? "";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xFFF2F3F5),
        appBar: _buildTitleBar(context),
        body: Padding(
          padding: EdgeInsets.all(16.0), // 这里设置内边距，可以根据需要调整数值
          child: Column(
            children: [_buildreportRow()],
          ),
        ),
      ),
      onWillPop: _onWillPop,
    );
  }

  Widget _buildreportRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 10, // 上边距
        bottom: 12, // 下边距
        left: 5, // 左边距
        right: 8, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              // 这里可以添加点击事件的处理逻辑
            },
            child: Container(
              padding: EdgeInsets.only(
                top: 0, // 上边距
                bottom: 0, // 下边距
                left: 10, // 左边距
                right: 5, // 右边距
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '设备开关',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        '关闭后，设备不在监控',
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ],
                  ),
                  Transform.scale(
                    scale: 0.8, // 缩小0.8倍
                    child: Switch(
                      value: _isSwitched == 1, // 1 表示开，0 表示关
                      activeTrackColor: SampleThemeConfigure.colorPrimary,
                      onChanged: (value) async {
                        print(value); // 打印开关状态
                        if (value) {
                          setState(() {
                            _isSwitched = 1; // 设置为 1 表示开
                          });
                        } else {
                          setState(() {
                            _isSwitched = 0; // 设置为 0 表示关
                          });
                        }
                        LogUtils.w(_isSwitched);

                        final resp = await InstructStandard.setDeviceSwitch(
                            _pipe, _isSwitched);
                        if (!mounted) return;
                        if (resp.success) {
                          bool eqswtich = await Api.instance.equploadrecord(
                              ID: _Eqid, state: "${_isSwitched}");
                          if (eqswtich) {
                            showToast("设置成功");
                          }
                        } else {
                          showToast("设备上线下线失败");
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          // InkWell(
          //   onTap: () {},
          //   child: Container(
          //     padding: EdgeInsets.only(
          //       top: 15, // 上边距
          //       bottom: 10, // 下边距
          //       left: 10, // 左边距
          //       right: 10, // 右边距
          //     ), // 设置内边距
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //       children: [
          //         Text(
          //           '让设备连接到其他WI-Fi',
          //           style: TextStyle(fontSize: 16),
          //         ),
          //         Icon(Icons.arrow_forward_ios,
          //             size: 16, color: Color(0xFF5a5a5a)),
          //       ],
          //     ),
          //   ),
          // ),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备时区',
                    style: TextStyle(fontSize: 16),
                  ),
                  Text(
                    _TZ,
                    style: TextStyle(color: Color(0xFF5a5a5a)),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备时间',
                    style: TextStyle(fontSize: 16),
                  ),
                  Row(
                    children: [
                      Text(
                        _TZTIME,
                        style: TextStyle(color: Color(0xFF5a5a5a)),
                      ),
                      // SizedBox(width: 5),
                      // Icon(Icons.arrow_forward_ios,
                      //     size: 16, color: Color(0xFF5a5a5a)),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      title: Text(
        "更多设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
